package com.yuyang.wifi.views;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.yuyang.wifi.MyApplication;
import com.yuyang.wifi.constant.AppConstant;
import com.yuyang.wifi.utils.DeviceInfoUtils;
import com.yuyang.wifi.utils.SpUtil;
import com.yuyang.wifi.utils.ToastUtils;
import com.qq.e.ads.rewardvideo2.ExpressRewardVideoAD;
import com.qq.e.ads.rewardvideo2.ExpressRewardVideoAdListener;
import com.qq.e.comm.util.AdError;

import java.util.Date;
import java.util.Locale;
import java.util.Map;

/**
 * created by mej
 * on 2020/12/2
 */
public class LoadYLHJiliVideoUtils implements ExpressRewardVideoAdListener,
        AdapterView.OnItemSelectedListener {


    private static final String TAG = "ylh_ad";

    private ExpressRewardVideoAD rewardVideoAD;
    private boolean adLoaded;//广告加载成功标志
    private boolean videoCached;//视频素材文件下载完成标志
    private OnAdCloseListener onAdCloseListener;

    static LoadYLHJiliVideoUtils instance = new LoadYLHJiliVideoUtils();
    private String mYlhJiLiChannel;
    private int adLoadCount;

    public static LoadYLHJiliVideoUtils getInstance() {
        return instance;
    }

    private Activity mContext;
    private boolean isVideoCompletePlay;
    private OnLoadFailureListener onLoadFailureListener;

    //一、加载优量汇激励视频
    //BDAdvanceBaseAppNative 绑定激励视频回调
    public void load(Activity context, String moduleName) {
        adLoadCount = 0;
        mContext = context;
        mYlhJiLiChannel = MyApplication.getYlhChannel(moduleName);
        initYLHAd();
    }

    private void initYLHAd() {
        rewardVideoAD = new ExpressRewardVideoAD(mContext, mYlhJiLiChannel, this);
        adLoaded = false;
        videoCached = false;
        // 2. 加载激励视频广告
        rewardVideoAD.loadAD();
    }


    @Override
    public void onAdLoaded() {
        adLoaded = true;
        Log.i(TAG, "ylh_success, adError========加载ad成功" + mYlhJiLiChannel);
        String msg = "load ad success ! expireTime = " + new Date(System.currentTimeMillis() +
                rewardVideoAD.getExpireTimestamp() - SystemClock.elapsedRealtime());
    }

    /**
     * 视频素材缓存成功，可在此回调后进行广告展示
     */
    @Override
    public void onVideoCached() {
        videoCached = true;
        Log.i(TAG, "onVideoCached");
    }

    @Override
    public void onShow() {
        isVideoCompletePlay = false;
    }

    @Override
    public void onExpose() {

    }


    @Override
    public void onReward(Map<String, Object> map) {

    }

    @Override
    public void onClick() {

    }

//    /**
//     * 激励视频触发激励（观看视频大于一定时长或者视频播放完毕）
//     */
//    @Override
//    public void onReward() {
//        Log.i(TAG, "onReward");
//    }


    /**
     * 激励视频播放完毕
     */
    @Override
    public void onVideoComplete() {
        isVideoCompletePlay = true;
        Log.i(TAG, "onVideoComplete");
    }

    @Override
    public void onClose() {
        initYLHAd();
        if (isVideoCompletePlay) {
            if (null != onAdCloseListener) {
                onAdCloseListener.onAdCloseListenerListener(true);
            }
        } else {
            if (null != onAdCloseListener) {
                onAdCloseListener.onAdCloseListenerListener(true);
            }
//            ToastUtils.showLongToast(mContext, "奖励领取失败，必须完整观看，1秒都不能少哦");
        }
    }


    /**
     * 广告流程出错
     */
    @Override
    public void onError(AdError adError) {
//        Log.i(TAG, "ylh_onError, adError========加载ad失败" + mYlhJiLiChannel);
//        if (adLoadCount < 25) {
//            adLoadCount++;
//            initYLHAd();
//        } else {
//            if (null != handlerLooper) {
//                handlerLooper.removeCallbacksAndMessages(null);
//            }
//        }
        String msg = String.format(Locale.getDefault(), "onError, error code: %d, error msg: %s",
                adError.getErrorCode(), adError.getErrorMsg());
        //  Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
        Log.i(TAG, "onError, adError=" + msg + onLoadFailureListener);
        if (null != onLoadFailureListener) {
            onLoadFailureListener.onLoadFailureListener();
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }


    //三、播放优量汇激励视频
    public void play() {
        Log.i(TAG, "ylh_success, rewardVideoAD===" + rewardVideoAD + "   adLoaded===" + adLoaded);
        if (rewardVideoAD != null && adLoaded) {//广告展示检查1：广告成功加载，此处也可以使用videoCached来实现视频预加载完成后再展示激励视频广告的逻辑
            if (!rewardVideoAD.hasShown()) {//广告展示检查2：当前广告数据还没有展示过
                long delta = 1000;//建议给广告过期时间加个buffer，单位ms，这里demo采用1000ms的buffer
                //广告展示检查3：展示广告前判断广告数据未过期
                if (SystemClock.elapsedRealtime() < (rewardVideoAD.getExpireTimestamp() - delta)) {
                    rewardVideoAD.showAD(null);
                    // ToastUtils.showLongToast(mContext, "请勿提前关闭或跳过，必须完整观看，1秒都不能少哦");
//                    ToastUtilsTime toastUtil3 = new ToastUtilsTime(mContext, R.layout.toast_center_horizontal, "看完视频可获得奖励");
//                    toastUtil3.show(5000);
                }
            }
        }
//        else {
//            startRoll();
//            initYLHAd();
//        }
    }

    private void startRoll() {
        // handlerLooper.removeCallbacksAndMessages(null);
        handlerLooper.sendEmptyMessageDelayed(0, 100);
    }

    Handler handlerLooper = new Handler() {
        public void handleMessage(Message msg) {
            if (rewardVideoAD != null && adLoaded) {//广告展示检查1：广告成功加载，此处也可以使用videoCached来实现视频预加载完成后再展示激励视频广告的逻辑
                handlerLooper.removeCallbacksAndMessages(null);
                if (!rewardVideoAD.hasShown()) {//广告展示检查2：当前广告数据还没有展示过
                    long delta = 1000;//建议给广告过期时间加个buffer，单位ms，这里demo采用1000ms的buffer
                    //广告展示检查3：展示广告前判断广告数据未过期
                    if (SystemClock.elapsedRealtime() < (rewardVideoAD.getExpireTimestamp() - delta)) {
                        rewardVideoAD.showAD(null);
                        ToastUtils.showLongToast(mContext, "请勿提前关闭或跳过，必须完整观看，1秒都不能少哦");
//                        ToastUtilsTime toastUtil3 = new ToastUtilsTime(mContext, R.layout.toast_center_horizontal, "看完视频可获得奖励");
//                        toastUtil3.show(5000);
                    }
                }
            } else {
                handlerLooper.sendEmptyMessageDelayed(0, 100);
//                Log.e("mej", "handleMessage:=== " + msg.obj);
//                if (adLoadCount < 5) {
//                    handlerLooper.sendEmptyMessageDelayed(0, 100);
//                } else {
//                    handlerLooper.removeCallbacksAndMessages(null);
//                }
            }
        }
    };


    public interface OnAdCloseListener {
        void onAdCloseListenerListener(boolean isPlayComplete);
    }

    public void setAdCloseListener(OnAdCloseListener onAdCloseListener) {
        this.onAdCloseListener = onAdCloseListener;
    }

    public interface OnLoadFailureListener {
        void onLoadFailureListener();
    }

    public void setLoadFailureListener(OnLoadFailureListener onLoadFailureListener) {
        this.onLoadFailureListener = onLoadFailureListener;
    }
}
